using System;
using UnityEngine;

public class CharacterHealth : MonoBehaviour
{
	public float currentHealth;

	[HideInInspector]
	private float maxHealth = 100f;

	public float sinceSpawn;

	public float sinceDamage;

	[SerializeField]
	private CharacterInformation info;

	[SerializeField]
	private CharacterFighting fighting;

	public UISprite sprHealthBar;

	public bool CanTakeDamage = true;

	public float headshotMultiplier = 1.25f;

	public float damageReduceMultiplier = 1f;

	private float sinceLastEnemyAttack;

	private CharacterInformation lastEnemyAttack;

	public Action<CharacterInformation, float> OnStickmanTakeDamage;

	public Action<CharacterInformation, CharacterInformation> OnStickmanDie;

	private void Update()
	{
		sinceSpawn += Time.deltaTime;
		sinceDamage += Time.deltaTime;
		sinceLastEnemyAttack += Time.deltaTime;
	}

	public void SetMaxHealth(float value)
	{
		maxHealth = value;
	}

	public void TakeDamage(float damage, CharacterInformation attacker, bool isHeadShot)
	{
		if (sinceSpawn < 0.5f || !info.isAlive || damage <= 0f || (sinceDamage <= 0.1f && damage < 500f) || !CanTakeDamage)
		{
			return;
		}
		info.ShowHit();
		sinceDamage = 0f;
		info.PlayGetHit();
		if (attacker != null)
		{
			sinceLastEnemyAttack = 0f;
			lastEnemyAttack = attacker;
		}
		if (isHeadShot)
		{
			fighting.DropWeapon();
			damage *= headshotMultiplier;
			if (attacker != null)
			{
				attacker.headShots++;
			}
		}
		if (!info.isDemo)
		{
			currentHealth -= damage * damageReduceMultiplier;
		}
		ShowHealthBar();
		if (currentHealth <= 0f)
		{
			Die(attacker);
		}
		if (OnStickmanTakeDamage != null)
		{
			OnStickmanTakeDamage(attacker, damage);
		}
	}

	public void Die(CharacterInformation attacker)
	{
		info.PlayDie();
		info.isAlive = false;
		fighting.DropWeapon();
		CharacterInformation arg = null;
		if (attacker != null)
		{
			attacker.kills++;
			arg = attacker;
		}
		else if (lastEnemyAttack != null && sinceLastEnemyAttack < 5f)
		{
			lastEnemyAttack.kills++;
			arg = lastEnemyAttack;
		}
		if (OnStickmanDie != null)
		{
			OnStickmanDie(info, arg);
		}
	}

	public void Respawn()
	{
		sinceLastEnemyAttack = 0f;
		lastEnemyAttack = null;
		info.isAlive = true;
		currentHealth = maxHealth;
		sinceSpawn = 0f;
		sinceDamage = 0f;
		info.isFallen = 0f;
		ShowHealthBar();
	}

	public void HealStickman()
	{
		currentHealth = maxHealth;
		ShowHealthBar();
	}

	private void ShowHealthBar()
	{
		if (sprHealthBar != null)
		{
			sprHealthBar.fillAmount = currentHealth / maxHealth;
		}
	}
}
